package com.fr.data;

import com.fr.base.Parameter;
import com.fr.general.data.TableDataException;
import com.fr.stable.StringUtils;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.*;

/**
 * @author liumingchun  17:45 2018-08-20
 */
public class BrandReportByDate extends AbstractTableData {
    /**
     * 字段名枚举YEAR
     */
    enum FIELD_NAME {
        DATE, BRAND_CODE, BRAND_NAME, SALES_AMOUNT, QUANTITY
    }

    /**
     * 列名数组，保存程序数据集所有列名
     */
    private String[] columNames;
    /**
     * 保存查询得到列值
     */
    private LinkedHashSet<LinkedHashMap<String, Object>> rowData;

    /**
     * 构造函数，定义表结构，该表有10个数据列，列名为column#0，column#1，。。。。。。column#9
     */
    public BrandReportByDate() {
        // 定义tableName参数
//        setDefaultParameters(new Parameter[]{new Parameter("tableName")});
        // 定义程序数据集列名
        this.parameters = new Parameter[]{new Parameter("bgnDate"), new Parameter("endDate")};
        // 填充字段名
        columNames = new String[FIELD_NAME.values().length];
        int i = 0;
        for (FIELD_NAME fieldName : FIELD_NAME.values()) {
            columNames[i] = fieldName.toString();
            i++;
        }
    }

    @Override
    public int getColumnCount() throws TableDataException {
        return columNames.length;
    }

    @Override
    public String getColumnName(int columnIndex) throws TableDataException {
        return columNames[columnIndex];
    }

    @Override
    public int getRowCount() throws TableDataException {
        queryData();
        return rowData.size();
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        queryData();
        int tempRowIndex = 0;
        for (LinkedHashMap<String, Object> row : rowData) {
            if (tempRowIndex == rowIndex) {
                return row.get(columNames[columnIndex]);
            }
            tempRowIndex += 1;
        }
        return null;
    }

    /**
     *  获取数据库连接 driverName和 url 可以换成您需要的
     * @return
     */
    public static Connection getConnection() {

        String driverName = "oracle.jdbc.driver.OracleDriver";
        String url = "jdbc:oracle:thin:@10.10.201.97:1521:crmngpsd";
        String username = "zyngprd";
        String password = "zyngprd";
        Connection con = null;
        try {
            Class.forName(driverName);
            con = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return con;
    }
    /**
     * 查询数据
     */
    public void queryData() {
        // 确保只被执行一次
        if (rowData != null) {
            return;
        }
        // 保存得到的数据库表名
        String bgnDate = parameters[0].getValue().toString();
        String endDate = parameters[1].getValue().toString();
//        String bgnDate = "2018-02-01";
//        String endDate = "2018-08-09";
        long start = System.currentTimeMillis();
        // 保存得到的结果集
        rowData = new LinkedHashSet<LinkedHashMap<String, Object>>();
        // 下面开始建立数据库连接，按照刚才的SQL语句进行查询
        Connection conn = getConnection();
        try {
            StringBuffer condition = new StringBuffer();
            if (StringUtils.isNotEmpty(bgnDate)) {
                condition.append(" and to_date('" + bgnDate.replaceAll("-", "") + "','yyyyMMdd') <= to_date(v.extend2,'yyyyMMdd')");
            }
            if (StringUtils.isNotEmpty(endDate)) {
                condition.append(" and  to_date('" + endDate.replaceAll("-", "") + "','yyyyMMdd') >= to_date(v.extend2,'yyyyMMdd')");
            }

            Statement stmt = conn.createStatement();
            //查询经销商Id
            String partyIdSql = "SELECT s.party_id FROM zdev_store_info s  GROUP BY s.party_id ";
            List partyList = new ArrayList();
            ResultSet partyIdReportRs = stmt.executeQuery(partyIdSql.toString());
            LinkedHashMap<String, Object> partyMap;
            while (partyIdReportRs.next()) {
                partyMap = new LinkedHashMap<String, Object>();
                partyMap.put("partyId", partyIdReportRs.getString(1));
                partyList.add(partyMap);
            }
            partyIdReportRs.close();

            List reportList = new ArrayList();
            for (int i = 0; i < partyList.size(); i++) {
                LinkedHashMap<String, Object> map = (LinkedHashMap<String, Object>) partyList.get(i);
                String partyId = String.valueOf(map.get("partyId"));
                //判断表是否存在
                String tableExist = "select count(1) from user_tables where table_name = 'ZDEV_SALES_DTL" + partyId + "_V2'";
                ResultSet tableExistResultSet = stmt.executeQuery(tableExist);
                String tableExistFlag = "";
                while (tableExistResultSet.next()) {
                    tableExistFlag = tableExistResultSet.getString(1);
                }
                if ("1".equals(tableExistFlag)) {
                    StringBuffer paymentReportSql = new StringBuffer();
                    paymentReportSql.append(" SELECT SUM(v.sales_amount) sales_amount,sum(v.extend7) quantity,S.BRAND_CODE, Z.FX_NAME BRAND_NAME, V.EXTEND2");
                    paymentReportSql.append(" FROM ZDEV_PS_DTL" + partyId + "_V2 V");
                    paymentReportSql.append(" LEFT JOIN ZDEV_STORE_INFO s on v.store_id = s.store_id AND  v.extend2 = s.extend1");
                    paymentReportSql.append(" LEFT JOIN zdev_param_content z ON z.fx_code = s.brand_code AND z.fl_code = '1003'");
                    paymentReportSql.append(" WHERE V.DIM_TYPE = '00' ");
                    paymentReportSql.append(condition);
                    paymentReportSql.append(" GROUP BY V.extend2,S.BRAND_CODE, Z.FX_NAME");
                    paymentReportSql.append(" ORDER BY V.extend2,S.BRAND_CODE");
                    ResultSet hourReportRs = stmt.executeQuery(paymentReportSql.toString());
                    while (hourReportRs.next()) {
                        LinkedHashMap<String, Object> info = new LinkedHashMap<String, Object>();
                        String brandCode = String.valueOf(hourReportRs.getString("BRAND_CODE"));
                        String brandName = String.valueOf(hourReportRs.getString("BRAND_NAME"));
                        String extend2 = String.valueOf(hourReportRs.getString("EXTEND2"));
                        BigDecimal salesAmount = hourReportRs.getBigDecimal("SALES_AMOUNT");
                        BigDecimal quantity = hourReportRs.getBigDecimal("QUANTITY") == null ? new BigDecimal(0) : hourReportRs.getBigDecimal("QUANTITY");
                        if (reportList.size() < 1) {
                            info.put("brandCode", brandCode);
                            info.put("brandName", brandName);
                            info.put("extend2", extend2);
                            info.put("salesAmount", salesAmount);
                            info.put("quantity", quantity);
                            reportList.add(info);
                        } else {
                            //如果有年月、品牌相同的，合并销售额、销售重量
                            boolean flag = true;
                            for (int j = 0; j < reportList.size(); j++) {
                                LinkedHashMap<String, Object> reportMap = (LinkedHashMap<String, Object>) reportList.get(j);
                                if (extend2.equals(reportMap.get("extend2")) && brandCode.equals(reportMap.get("brandCode"))) {
                                    flag = false;
                                    reportMap.put("salesAmount", salesAmount.add((BigDecimal) reportMap.get("salesAmount")));
                                    reportMap.put("quantity", quantity.add((BigDecimal) reportMap.get("quantity") == null ? new BigDecimal(0) : (BigDecimal) reportMap.get("quantity")));
                                }
                            }
                            //年月小时均不同，添加进集合中成为新的元素
                            if (flag) {
                                info.put("brandCode", brandCode);
                                info.put("brandName", brandName);
                                info.put("extend2", extend2);
                                info.put("salesAmount", salesAmount);
                                info.put("quantity", quantity);
                                reportList.add(info);
                            }
                        }
                    }
                    hourReportRs.close();
                }
            }
            //按照枚举类放置数据
            for (int i = 0; i < reportList.size(); i++) {
                LinkedHashMap<String, Object> reportMap = (LinkedHashMap<String, Object>) reportList.get(i);
                LinkedHashMap<String, Object> row = new LinkedHashMap<String, Object>();
                row.put(FIELD_NAME.DATE.toString(), reportMap.get("extend2"));
                row.put(FIELD_NAME.BRAND_CODE.toString(), reportMap.get("brandCode"));
                row.put(FIELD_NAME.BRAND_NAME.toString(), reportMap.get("brandName"));
                row.put(FIELD_NAME.SALES_AMOUNT.toString(), reportMap.get("salesAmount"));
                row.put(FIELD_NAME.QUANTITY.toString(), reportMap.get("quantity"));
                rowData.add(row);
            }
            long end = System.currentTimeMillis();
            System.out.println("耗时：" + String.valueOf((end - start) / 1000) + "s");
            System.out.println("===================================s");
            // 释放数据库资源
            stmt.close();
            conn.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 释放一些资源，因为可能会有重复调用，所以需释放valueList，将上次查询的结果释放掉
    @Override
    public void release() throws Exception {
        super.release();
        this.rowData = null;
    }
}
